<template>
  <div class="chat-container">
    <div class="chat-header">
      <div class="chat-title">
        <h1>Ai 机器人</h1>
        <span class="chat-subtitle">共 {{ messages.length || 0 }} 条对话</span>
      </div>
      <div class="header-actions">
        <button class="icon-button"><i class="icon-refresh"></i></button>
        <button class="icon-button"><i class="icon-edit"></i></button>
        <button class="icon-button"><i class="icon-share"></i></button>
        <button class="icon-button"><i class="icon-fullscreen"></i></button>
      </div>
    </div>
    <div class="messages" ref="scrollContainer">
      <div v-for="(msg, index) in messages" :key="index" class="message"
           :class="msg.role === 'user' ? 'user-message-container' : 'bot-message-container'">
        <div class="message-content-wrapper">
          <div class="avatar" :class="msg.role === 'user' ? 'user-avatar' : 'bot-avatar'">
            <span v-if="msg.role === 'user'">👤</span>
            <span v-else>🤖</span>
          </div>
          <div :class="msg.role === 'user' ? 'user-message' : 'bot-message'">
            <v-md-editor v-model="msg.content" height="auto" mode="preview"></v-md-editor>
          </div>
        </div>
        <div class="message-time" v-if="msg.time">{{ msg.time }}</div>
      </div>
      <!-- <span class="cursor">|</span> -->
    </div>
    <div class="input-container">
      <div class="input-toolbar">
        <button class="toolbar-button" v-for="item in prompt" :key="item" @click="handlePrompt(item)">{{
            item
          }}
        </button>
        <!--<button class="toolbar-button"><i class="icon-image"></i></button>-->
        <!--<button class="toolbar-button"><i class="icon-sticker"></i></button>-->
        <!--<button class="toolbar-button"><i class="icon-code"></i></button>-->
        <!--<button class="toolbar-button"><i class="icon-more"></i></button>-->
      </div>
      <div class="input-area">
        <input ref="inputRef" type="text" v-model="text" @keyup.enter="handleBtn" :disabled="isTyping"
               placeholder="Enter 发送，Shift + Enter 换行，/ 触发补全，. 触发命令">
        <button @click="handleBtn" :disabled="isTyping" class="send-button">
          <i class="icon-send"></i> 发送
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import {getCache} from "@/utils/useCache";

export default {
  name: 'App',
  data() {
    return {
      text: "",
      messages: [], // 用于存储用户和机器人的消息
      ws: null,
      typingIndex: 0,
      currentMessage: "", // 当前正在打字的消息
      isTyping: false, // 用于控制打字机效果的状态
      messageQueue: [], // 消息队列
      isMobile: false, // 添加设备类型标识
      prompt: ['减肥可以吃哪些食物？', '怎么保持良好的睡眠？', '正常人一天喝几杯水？', '睡觉磨牙什么原因？']
    };
  },
  created() {
    // 检测设备类型
    const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
    this.isMobile = isMobile;
    console.log('设备类型:', isMobile ? '移动设备' : 'PC设备');
  },
  mounted() {
    // 组件加载完成后自动聚焦到输入框
    this.focusInput();
    const _this = this;
    // this.ws = new WebSocket("ws://localhost:9091/myWs?1");
    // this.ws = new WebSocket("/api/myWs?" + getCache('USERINFO').id);
    this.ws = new WebSocket("ws://115.190.31.221:9090/myWs?" + getCache('USERINFO').id);
    this.ws.onopen = function () {
      console.log('WebSocket connection opened');
    };
    this.ws.onmessage = function (msg) {
      // console.log('Received message:', msg.data);
      _this.messageQueue.push(msg.data); // 将消息放入队列
      _this.processMessageQueue(); // 处理消息队列
    }
    this.ws.onclose = function () {
      console.log('WebSocket connection closed');
    };
  },
  beforeDestroy() {
    if (this.ws) {
      this.ws.close();
    }
  },
  updated() {
    this.focusInput();
  },
  methods: {
    scrollToBottom() {
      const container = this.$refs.scrollContainer;
      if (container) {
        this.$nextTick(() => {
          container.scrollTop = container.scrollHeight;
        });
      }
    },
    focusInput() {
      // 确保输入框存在后聚焦
      this.$nextTick(() => {
        if (this.$refs.inputRef) {
          this.$refs.inputRef.focus();
        }
      });
    },
    handleBtn() {
      if (this.ws.readyState === WebSocket.OPEN && this.text.trim() !== "") {
        this.messages.push({role: "user", content: this.text}); // 添加用户消息
        this.ws.send(JSON.stringify(this.messages));
        this.messages.push({role: "assistant", content: "",}); // 添加回复消息
        this.text = ""; // 发送后清空输入框
        this.scrollToBottom(); // 添加这一行，发送消息后滚动到底部
      }
    },
    handlePrompt(e) {
      this.text = e;
    },
    processMessageQueue() {
      if (this.isTyping || this.messageQueue.length === 0) {
        return; // 如果正在打字或队列为空，直接返回
      }
      const nextMessage = this.messageQueue.shift(); // 从队列中取出一条消息
      this.handleMessages(nextMessage); // 处理消息
      this.scrollToBottom(); // 添加这一行，处理新消息时滚动到底部
    },
    handleMessages(newMessage) {
      this.currentMessage = newMessage; // 保存当前消息
      this.typingIndex = 0; // 重置索引
      this.isTyping = true; // 开始打字机效果
      this.typeWriterEffect(() => {
        console.log("打字完成");
        this.scrollToBottom(); // 添加这一行，打字完成后滚动到底部
      });
    },
    typeWriterEffect(callback) {
      const message = this.currentMessage; // 获取当前消息
      const typeNextChar = () => {
        if (this.typingIndex < message.length) {
          this.messages[this.messages.length - 1].content += message[this.typingIndex++];
          this.$nextTick(() => {
            this.scrollToBottom(); // 添加这一行，每次添加字符后滚动到底部
            requestAnimationFrame(typeNextChar);
          });
        } else {
          this.isTyping = false; // 完成打字机效果
          if (callback) {
            callback(); // 调用回调函数
          }
          this.processMessageQueue(); // 继续处理队列中的消息
        }
      };
      typeNextChar();
    }
  }
}
</script>

<style scoped>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
}

.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  max-width: 1200px;
  margin: 0 auto;
  border-left: 1px solid #e0e0e0;
  border-right: 1px solid #e0e0e0;
  background-color: #f5f5f5;
}

.chat-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 20px;
  border-bottom: 1px solid #e0e0e0;
  background-color: #ffffff;
}

.chat-title {
  display: flex;
  flex-direction: column;
}

.chat-title h1 {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
}

.chat-subtitle {
  font-size: 12px;
  color: #666;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.icon-button {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  border: 1px solid #e0e0e0;
  background-color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.icon-button:hover {
  background-color: #f5f5f5;
}

.messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background-color: #f5f5f5;
}

.message {
  margin-bottom: 20px;
  display: flex;
  flex-direction: column;
  position: relative;
}

.message-content-wrapper {
  display: flex;
  flex-direction: column;
  width: 100%;
  align-items: flex-start;
}

.user-message-container {
  align-items: flex-end;
}

.bot-message-container {
  align-items: flex-start;
}

.user-message-container .message-content-wrapper {
  align-items: flex-end;
}

.bot-message-container .message-content-wrapper {
  align-items: flex-start;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  margin-bottom: 5px;
  flex-shrink: 0;
}

.user-avatar {
  background-color: #a0d911;
}

.bot-avatar {
  background-color: #ffffff;
  border: 1px solid #e0e0e0;
}

.user-message {
  background-color: #dcf8c6;
  border-radius: 18px 0 18px 18px;
  max-width: 70%;
  width: 100%;
  position: relative;
  border: 1px solid #c7e9b0;
  word-break: break-word;
  overflow: hidden;
}

.bot-message {
  background-color: #ffffff;
  border-radius: 0 18px 18px 18px;
  max-width: 70%;
  width: 100%;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  position: relative;
  border: 1px solid #e0e0e0;
  word-break: break-word;
  overflow: hidden;
}

.message-time {
  font-size: 10px;
  color: #999;
  margin-top: 5px;
  align-self: flex-end;
}

/* 确保v-md-editor内容不会溢出 */
.user-message :deep(.v-md-editor),
.bot-message :deep(.v-md-editor) {
  max-width: 100%;
  width: 100%;
  overflow-wrap: break-word;
  border: none !important;
  overflow: hidden;
}

.user-message :deep(.v-md-editor) {
  background-color: #dcf8c6 !important;
  border-radius: 18px 0 18px 18px !important;
}

.bot-message :deep(.v-md-editor) {
  background-color: #ffffff !important;
  border-radius: 0 18px 18px 18px !important;
}

/* 确保v-md-editor的预览区域也遵循圆角设置 */
.user-message :deep(.v-md-editor .v-md-editor__preview) {
  border-radius: 18px 0 18px 18px !important;
  padding: 10px 15px;
  width: 100%;
  min-width: 400px;
}

.bot-message :deep(.v-md-editor .v-md-editor__preview) {
  border-radius: 0 18px 18px 18px !important;
  padding: 10px 15px;
  width: 100%;
  min-width: 400px;
}

.user-message :deep(.v-md-editor .v-md-editor__preview-wrapper),
.bot-message :deep(.v-md-editor .v-md-editor__preview-wrapper) {
  padding: 0;
  width: 100%;
  border-radius: inherit !important;
}

/* 确保消息容器本身也有圆角 */
.user-message {
  border-radius: 18px 0 18px 18px !important;
  overflow: hidden;
}

.bot-message {
  border-radius: 0 18px 18px 18px !important;
  overflow: hidden;
}

/* 优化列表显示 */
.user-message :deep(ul),
.bot-message :deep(ul) {
  padding-left: 20px;
}

.user-message :deep(li),
.bot-message :deep(li) {
  margin-bottom: 8px;
}

/* 确保内容能够撑开消息框 */
.user-message :deep(p),
.bot-message :deep(p) {
  width: 100%;
  white-space: normal;
}

.input-container {
  background-color: #f0f0f0;
  border-top: 1px solid #e0e0e0;
}

.input-toolbar {
  display: flex;
  padding: 8px 15px;
  border-bottom: 1px solid #e0e0e0;
}

.toolbar-button {
  border: none;
  /*width: 32px;*/
  width: auto;
  height: 32px;
  border-radius: 16px;
  background-color: #fff;
  padding: 0 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  margin-right: 5px;
}

.toolbar-button:hover {
  background-color: #e0e0e0;
}

.input-area {
  display: flex;
  padding: 15px;
}

.cursor {
  display: inline-block;
  margin-left: 5px;
  opacity: 1;
  animation: blink 1s steps(1) infinite;
}

@keyframes blink {
  50% {
    opacity: 0;
  }
}

input[type="text"] {
  padding: 12px 15px;
  border: 1px solid #ddd;
  border-radius: 24px;
  width: 85%;
  font-size: 14px;
  margin-right: 10px;
  outline: none;
}

.send-button {
  padding: 8px 15px;
  background-color: #128C7E;
  color: white;
  border: none;
  border-radius: 24px;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.send-button:hover {
  background-color: #0e7a6d;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-container {
    border: none;
  }

  .user-message,
  .bot-message {
    max-width: 70%;
  }

  .avatar {
    width: 32px;
    height: 32px;
    font-size: 16px;
  }

  input[type="text"] {
    width: 75%;
  }
}

/* 图标样式 */
.icon-refresh:before {
  content: "↻";
}

.icon-edit:before {
  content: "✎";
}

.icon-share:before {
  content: "↗";
}

.icon-fullscreen:before {
  content: "⛶";
}

.icon-emoji:before {
  content: "😊";
}

.icon-image:before {
  content: "🖼";
}

.icon-sticker:before {
  content: "🏷";
}

.icon-code:before {
  content: "⌨";
}

.icon-more:before {
  content: "⋯";
}

.icon-send:before {
  content: "↑";
}

</style>
